using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Write.Commands;
using Work.Domain;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Write.CommandHandlers
{
    /// <summary>
    /// 创建病历处理器
    /// </summary>
    public class CreateMedicalRecordCommandHandler : IRequestHandler<CreateMedicalRecordCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<MedicalRecord> _medicalRecordRepo;
        private readonly IBaseRepository<Appintment> _appointmentRepo;

        public CreateMedicalRecordCommandHandler(
            IBaseRepository<MedicalRecord> medicalRecordRepo,
            IBaseRepository<Appintment> appointmentRepo)
        {
            _medicalRecordRepo = medicalRecordRepo;
            _appointmentRepo = appointmentRepo;
        }

        public async Task<ApiResult<int>> Handle(CreateMedicalRecordCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 1. 验证预约是否存在
                var appointment = await _appointmentRepo.GetById(request.AppointmentId);
                if (appointment == null)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "预约不存在";
                    result.Data = 0;
                    return result;
                }

                // 2. 检查是否已有病历
                var existing = await _medicalRecordRepo.GetAll()
                    .FirstOrDefaultAsync(m => m.AppointmentId == request.AppointmentId, cancellationToken);

                if (existing != null)
                {
                    // 已有病历，直接更新（不限制状态，允许随时修改）
                    existing.ChiefComplaint = request.ChiefComplaint;
                    existing.PresentIllness = request.PresentIllness;
                    existing.PastHistory = request.PastHistory;
                    existing.Diagnosis = request.Diagnosis;
                    existing.Treatment = request.Treatment;
                    existing.Prescription = request.Prescription;
                    existing.Advice = request.Advice;
                    existing.Status = request.Status;
                    existing.Remarks = request.Remarks;
                    existing.UpdateTime = DateTime.Now;

                    await _medicalRecordRepo.UpdateAsync(existing);

                    // 根据状态更新预约状态
                    if (request.Status == "已完成")
                    {
                        appointment.RecordStatus = "已就诊";
                    }
                    else
                    {
                        appointment.RecordStatus = "进行中";
                    }
                    await _appointmentRepo.UpdateAsync(appointment);

                    result.Code = ApiEnum.成功;
                    result.Message = "病历更新成功";
                    result.Data = existing.RecordId;
                    return result;
                }

                // 3. 创建新病历
                var medicalRecord = new MedicalRecord
                {
                    AppointmentId = request.AppointmentId,
                    PatientId = request.PatientId,
                    CardNumber = request.CardNumber,
                    PatientName = request.PatientName,
                    DoctorName = request.DoctorName,
                    Department = request.Department,
                    ChiefComplaint = request.ChiefComplaint,
                    PresentIllness = request.PresentIllness,
                    PastHistory = request.PastHistory,
                    Diagnosis = request.Diagnosis,
                    Treatment = request.Treatment,
                    Prescription = request.Prescription,
                    Advice = request.Advice,
                    VisitDate = request.VisitDate ?? appointment.VisitDate,
                    CreateTime = DateTime.Now,
                    Status = request.Status ?? "草稿",
                    Remarks = request.Remarks
                };

                var rows = await _medicalRecordRepo.AddAsync(medicalRecord);

                if (rows > 0)
                {
                    // 如果病历完成，更新预约状态
                    if (request.Status == "已完成")
                    {
                        appointment.RecordStatus = "已就诊";
                        await _appointmentRepo.UpdateAsync(appointment);
                    }
                    else
                    {
                        appointment.RecordStatus = "进行中";
                        await _appointmentRepo.UpdateAsync(appointment);
                    }

                    result.Code = ApiEnum.成功;
                    result.Message = "病历保存成功";
                    result.Data = medicalRecord.RecordId;
                }
                else
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "病历保存失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"保存失败：{ex.Message}";
                result.Data = 0;
            }

            return result;
        }
    }
}

